# import os
# import os.path as op
# import sys
from math import floor
import Tkinter as TK
from telnetlib import Telnet as T
from socket import timeout
from tkFileDialog import asksaveasfile
import tkMessageBox as MB
import getdata as GD
from time import *
import datetime as DT

prompt = "S>"
max = 20

def figure_out_restart(date, time):
	now = DT.datetime(date.year, date.month, date.day,
					  time.hour, time.minute)
	dt = DT.timedelta(seconds=15*60)
	temp = now + dt
	minute = 15*floor(temp.minute/15.0)
	return DT.datetime(temp.year, temp.month, temp.day, temp.hour, int(minute))

def Lb_doubleclick(event):
	global selection
	selection = Lb.selection_get()
	
def get_serial_ports(connection):
	connection.write("who\r\n")
	connection.read_until("\r\n", max)
	tmp = connection.read_until("\r\n", max)
	# print tmp
	pids = []
	while "#>" not in tmp:
		# print "inner while loop"
		tmp = connection.read_until("\r\n", max)
		# print tmp
		if "serial" in tmp:
			pids.append(tmp[0])
	return pids

def kill_serial_ports(connection, pids):
	for pid in pids:
		connection.write("kill %s\r\n"%pid)
		tmp = connection.read_until("\r\n", max)
		# print tmp

class kill_timeout(timeout):
	def __init__(self):
	    timeout.__init__(self)

global selection
IPsPORTs = {"MUK": ("166.140.17.138", 8001),
			"MAN": ("165.151.151.19", 8001),
			"SQS": ("166.140.038.220", 4002),
			"SQB": ("166.140.038.220", 4001),
			"WLP": ("166.130.17.242", 8001)}
keys = IPsPORTs.keys()
vals = IPsPORTs.values()
Lb = TK.Listbox()
for i in range(len(keys)):
	Lb.insert(i+1, keys[i] + ' ' + vals[i][0] + ':' + str(vals[i][1]))
Lb.pack()
Lb.bind('<Double-1>', Lb_doubleclick)
MB.showinfo('', "Double-click on selection, then close panel (click on red X)")
TK.mainloop()
ipport = selection[4:].split(':')
ipport = (ipport[0], int(ipport[1]))
print
print ipport
print
try: # First, kill serial ports if more than one
	tn23 = T(ipport[0], 23, 20)
	tmp = tn23.read_all()
	# tmp = tn23.read_until("login:", max)
	# print tmp
	# tn23.write("admin\r\n")
	# tmp = tn23.read_until("password:", max)
	# print tmp
	# tn23.write("strix!12\r\n")
	ports_killed = False; out_tries = 0
	while (not ports_killed) and (out_tries < max):		
		print
		print "out_tries: ", out_tries
		out_tries += 1		
		tmp = tn23.read_until("#>", max)
		print tmp
		pids = get_serial_ports(tn23)
		print pids
		npids = len(pids); in_tries = 0
		if npids == 0: print "No serial connections found"
		while (npids > 1) and (in_tries < max/2): 
			print "in_tries: ", in_tries
			in_tries += 1		
			kill_serial_ports(tn23, pids)
			pids = get_serial_ports(tn23)
			npids = len(pids)			
			if npids == 1: npids = 2 # If this is true, we haven't killed them all
		if npids > 1: # if this is true, we must have tried too many times
			raise kill_timeout
		else:
			ports_killed = True
	if out_tries == max:
		raise kill_timeout
	# Just to be sure
	pids = get_serial_ports(tn23)
	if len(pids) > 1:
		raw_input("Sorry, something wrong w/ your kill algorithm")
except timeout:
	GD.timeout_exception("Couldn't get in on port 23 in " + str(max) + 
	" tries.  Giving up.\n")
except kill_timeout:
	GD.timeout_exception("Couldn't kill serial ports in " + str(max) + 
	" tries.  Giving up.\n")

tn, data, date, time = GD.getdata(ipport, max)
data = str(data)
if tn is not None:
	try: # issue delayed logging restart
		print "Issuing restart commands"
		restart = figure_out_restart(date, time)
		cmnd = restart.date().strftime("startmmddyy=%m%d%y\r\n")
		tn.write(cmnd)
		tmp = tn.read_until(prompt, max); data += tmp; print tmp
		cmnd = restart.time().strftime("starthhmmss=%H%M%S\r\n")
		tn.write(cmnd)
		tmp = tn.read_until(prompt, max); data += tmp; print tmp
		temp = "startlater\r\n"
		tn.write(temp)
		temp = tn.read_until(prompt, max); data += temp; print temp
		if "start time =" not in temp:
			raise timeout
		if data[0:4] is not 'None':
			try:
				print "Data retrieved, writing to file"
				fo = asksaveasfile()
				fo.write(data)
				fo.flush()
				fo.close()
				print "Data written successfully to:"
				print fo.name
			except IOError:
				t, v, b = sys.exc_info()
				MB.showerror("Sorry!", 
					"Couldn't open file to write data.  Giving up.\n" + 
					str(t) + " " + str(v) + "\n" + str(b))
#				tn.close()
		else:
			print "Sorry, no data returned, not sure why."
			print "Please contact david.goldsmith@ecy.wa.gov for assistance."
	except timeout:
		GD.timeout_exception("Couldn't confirm restart.  Giving up.\n")
#		tn.close()
	x = tn.close()
	print x
else:
	MB.showerror("Sorry!", 
		"Couldn't open telnet connection to " + ipport[0] + ", port " +
		str(ipport[1]) + ".")
y = tn23.close()
print y
raw_input("Press Enter to close console and quit.") 